#!/bin/bash

make_sure_dir_exist () { [ -d $1 ] || mkdir -p $1;}

echo "Running postgres forever"
forever () {
    while [ 1 ]
    do
        # make postgres run forever
        if [[ `ps aux | grep postgres | wc -l` -lt 2 ]]; then
            su postgres -c "/usr/lib/postgresql/9.4/bin/postgres -c config_file=/opt/etc/postgresql.conf" &
        fi
        sleep 3
    done
}

# make sure dir is exist
make_sure_dir_exist "/opt/log/os_stdout"
make_sure_dir_exist "/opt/log/os_stderr"
make_sure_dir_exist "/opt/data/postgres"
make_sure_dir_exist "/opt/data/run/postgresql/9.4-main.pg_stat_tmp"

# make database exist
if [[ `ls /opt/data/postgres/ | wc -l` -lt 1 ]]; then
    # make sure the access right
    chmod -R 700 /opt/data/postgres
    chown -R postgres /opt/data/postgres

    chmod -R 700 /opt/data/run/postgresql/9.4-main.pg_stat_tmp
    chown -R postgres /opt/data/run/postgresql/9.4-main.pg_stat_tmp

    # init db
    su postgres -c "/usr/lib/postgresql/9.4/bin/initdb -D /opt/data/postgres"
    # su postgres -c "/etc/init.d/postgresql start && psql --command \"CREATE USER $USERNAME WITH PASSWORD '$PASSWORD'\""
    su postgres -c "/etc/init.d/postgresql start && psql --command \"ALTER USER $USERNAME WITH PASSWORD '$PASSWORD'\""
fi
# out put system log
NOW=$(date +%Y-%m-%d-%H-%M-%S)
forever > "/opt/log/os_stdout/$NOW.log" 2> "/opt/log/os_stderr/$NOW.log"
